const httpStatus = require('http-status');
const catchAsync = require('../utils/catchAsync');
const { authService, userService, tokenService, emailService } = require('../services');

/**
 * 用户注册
 */
const register = catchAsync(async (req, res) => {
  const user = await userService.createUser(req.body);
  const tokens = await tokenService.generateAuthTokens(user, 'user');
  res.status(httpStatus.CREATED).send({ user, tokens });
});

/**
 * 用户登录
 */
const login = catchAsync(async (req, res) => {
  const { email, password } = req.body;
  const user = await authService.login(email, password);
  const tokens = await tokenService.generateAuthTokens(user, 'user');
  res.send({ user, tokens });
});

/**
 * 用户登出
 */
const logout = catchAsync(async (req, res) => {
  await authService.logout(req.body.refreshToken);
  res.status(httpStatus.NO_CONTENT).send();
});

/**
 * 刷新令牌
 */
const refreshTokens = catchAsync(async (req, res) => {
  const tokens = await authService.refreshAuth(req.body.refreshToken);
  res.send({ ...tokens });
});

/**
 * 忘记密码
 */
const forgotPassword = catchAsync(async (req, res) => {
  const resetPasswordToken = await tokenService.generateResetPasswordToken(req.body.email);
  // 如果集成了邮件服务，这里需要发送邮件
  // await emailService.sendResetPasswordEmail(req.body.email, resetPasswordToken);
  res.status(httpStatus.NO_CONTENT).send();
});

/**
 * 重置密码
 */
const resetPassword = catchAsync(async (req, res) => {
  await authService.resetPassword(req.query.token, req.body.password);
  res.status(httpStatus.NO_CONTENT).send();
});

/**
 * 验证邮箱
 */
const verifyEmail = catchAsync(async (req, res) => {
  await authService.verifyEmail(req.query.token);
  res.status(httpStatus.NO_CONTENT).send();
});

/**
 * 微信小程序登录
 * @POST /api/user/wx-login
 * @param {string} req.body.code - 微信临时登录凭证
 * @returns {Object} userId, token, nickname, avatar, isNewUser
 */
const wxLogin = catchAsync(async (req, res) => {
  const { code } = req.body;
  const { user, isNewUser } = await authService.loginWithWechat(code);
  
  // 指定用户类型为'user'
  const tokens = await tokenService.generateAuthTokens(user, 'user');
  
  console.log('微信小程序用户登录成功:', {
    userId: user.id,
    isNewUser,
    tokenExpires: tokens.access.expires
  });
  
  res.send({
    error: 0,
    body: {
      userId: user.id,
      token: tokens.access.token,
      nickname: user.nickname || '',
      avatar: user.avatar || '',
      isNewUser
    },
    message: '登录成功'
  });
});

module.exports = {
  register,
  login,
  logout,
  refreshTokens,
  forgotPassword,
  resetPassword,
  verifyEmail,
  wxLogin,
}; 